<?php

	namespace Phptricks\system\library\upload;

/*
	 * To change this license header, choose License Headers in Project Properties.
	 * To change this template file, choose Tools | Templates
	 * and open the template in the editor.
	 */
	/**
	 * Description of models
	 *
	 * @author Sammy Guergachi <sguergachi at gmail.com>
	 */
	use Phptricks\system\core\library\library;
	use Phptricks\system\library\PhptricksExceptions\PhptricksExceptions as Exc;
	use Phptricks\system\library\request_variables\request_variables as request_variables;
	use Phptricks\system\library\loaders\loader as loaders;
	use Phptricks\system\library\security\security as security;

	class upload implements library{

		public $_courrnt_item = '';
		public $_security;
		public $_request_variables;
		private static $_instance = null;
		private $upload_dir;

		public static function &getinstance(){
			if (self::$_instance === null) {
				self::$_instance = new \Phptricks\system\library\upload\upload();
			}
			return self::$_instance;
		}

		public function _initialize($upload_dir){
			$this->upload_dir = $upload_dir;
		}

		public function __construct(){
			$this->_security = security::getinstance();
			$this->_request_variables = request_variables::getinstance();
		}

		public function uploads($field_name, $dir_path = '', $security = true){
			$return_files = array();
			if (!isset($field_name) || empty($field_name)) {
				$field_name = 'file_upload';
			}
			if (empty($dir_path)) {
				$dir_path = $this->upload_dir;
			}
			$upload_files = $this->_request_variables->_files[$field_name];
			foreach ($upload_files['name'] as $keys => $value) {
				$upload_file_name = $value;
				$upload_pathinfo = pathinfo($value);
				$upload_file_type = $upload_pathinfo['extension'];

				$upload_random_name = $dir_path . date("Y") . date("m") . date("d") . "-" . date("H") . date("i") . date("s") . "-" . rand(date("i"), date("s")) * rand(date("i"), date("s")) . "." . $upload_file_type;
				if (!empty($upload_file_name)) {
					try {
						if (move_uploaded_file($upload_files['tmp_name'][$keys], $upload_random_name) == true) {
							$this->_courrnt_item = $upload_random_name;
							$return_files[] = $upload_random_name;
							if (is_array(getimagesize($this->_courrnt_item))) {
								if ($security == true) {
									$this->_security->check_files($this->_courrnt_item);
								}
							}
						}
					} catch (\Exception $exc) {
						$return_files[] = $exc->getTraceAsString();
					}
				} else {
					$return_files[] = "لم تقم بإختيار الملف";
					return false;
				}
			}
			return $return_files;
		}

	}
	